import {Base64} from 'js-base64';

const saveEvent = (type: string, name: string, value: any) => {
    // 如果value存在则为赋值   否则为取值
    if (typeof value !== 'undefined') {
        let val: string = '';

        if (typeof value === 'object') {
            val = JSON.stringify(value);
        } else if (typeof value === 'string') {
            val = value;
        }

        window[type].setItem(name, Base64.encode(val));
    } else {
        let result = window[type].getItem(name);

        // 如果值不存在
        if (result === undefined || result === 'undefined' || result === null || !result) {
            return false;
        }

        try {
            result = JSON.parse(Base64.decode(result));
        } catch (err) {
            console.log(err);
            return false;
        }

        return result;
    }
}

/**
 * SessionStorage 本地储存操作   关闭浏览器后删除
 * @param { String }    name      数据名称
 * @param { Object }    value     数据值
 */
export const ssStorage = (name: string, value?: any) => {
    if (!name) {
        console.warn('ssStorage params first is required！');
    }

    return saveEvent('sessionStorage', name, value);
};
/**
 * SessionStorage 本地储存操作   永久储存
 * @param { String }    name      数据名称
 * @param { Object }    value     数据值
 */
export const locStorage = (name: string, value?: any) => {
    return saveEvent('localStorage', name, value);
}
